﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Linq.Expressions;
using System.IO;
using Word = Microsoft.Office.Interop.Word;
using System.Text;

public partial class Manage_StatArticle : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            #region 绑定年、月、日
            for (int i = 2012; i <= 2007 + 10 || i <= DateTime.Now.Year + 2; i++)
            {
                Year1.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
                Year2.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
            }
            for (int i = 1; i <= 12; i++)
            {
                Month1.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
                Month2.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
            }
            for (int i = 1; i <= 31; i++)
            {
                Day1.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
                Day2.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
            }

            Year2.SelectedValue = Convert.ToString(DateTime.Now.Year);
            Month2.SelectedValue = Convert.ToString(DateTime.Now.Month);
            Day2.SelectedValue = Convert.ToString(DateTime.Now.Day);
            #endregion

            #region 加载单位信息
            XmlDocument doc = new XmlDocument();
            doc.Load(Toolkit.GetRealDataFilePath("Department.xml"));
            XmlElement root = doc.DocumentElement;

            //选择县区
            foreach (XmlNode node in root.SelectNodes("/Root/District"))
            {
                TreeNode tn1 = new TreeNode();
                string district = node.Attributes["name"].Value;
                tn1.Text = district;
                tn1.Value = district;
                tn1.NavigateUrl = "javascript:void(0)";

                Departments.Nodes.Add(tn1);
                tn1.CollapseAll();


                //加载其单位
                foreach (XmlNode node2 in root.SelectNodes(string.Format("/Root/District[@name='{0}']//Depart", district)))
                {
                    TreeNode tn2 = new TreeNode();
                    string depart = node2.Attributes["name"].Value;

                    tn2.Value = "D:" + depart;
                    tn2.Text = depart;
                    tn2.NavigateUrl = "javascript:void(0)";

                    tn1.ChildNodes.Add(tn2);
                    tn2.CollapseAll();
                }
            }
            #endregion
        }
    }
    protected void Export_Click(object sender, EventArgs e)
    {
        DateTime st = DateTime.Parse(string.Format("{0}年{1}月{2}日", Year1.SelectedValue, Month1.SelectedValue, Day1.SelectedValue));
        DateTime ed = DateTime.Parse(string.Format("{0}年{1}月{2}日", Year2.SelectedValue, Month2.SelectedValue, Day2.SelectedValue));

        Word.Application app = null;
        Word.Document doc = null;

        object ms = Type.Missing;

        try
        {
            StringBuilder sb = new StringBuilder();
            #region 在树控件中查询所有单位的名称
            foreach (TreeNode n1 in Departments.Nodes)
            {
                string val1 = n1.Value;
                if (n1.Checked && val1.StartsWith("D:"))
                {
                    sb.Append(" " + val1.Substring(2));
                }

                foreach (TreeNode n2 in n1.ChildNodes)
                {
                    string val2 = n2.Value;
                    if (n2.Checked && val2.StartsWith("D:"))
                    {
                        sb.Append(" " + val2.Substring(2));
                    }
                }
            }
            #endregion

            CmsDataContext db = new CmsDataContext();
            var q = from aA in db.Article
                    where aA.Verified != null && aA.Published.CompareTo(st) >= 0 && aA.Published.CompareTo(ed) <= 0
                    select aA;

            #region 查询条件
            Expression<Func<Article, bool>> lmbda = PredicateBuilder<Article>.CreatePredicate(new string[] { "Belong" }, sb.ToString().Trim(), "aA");
            var p = q.Where(lmbda);
            #endregion

            string path = Toolkit.MappingPath(Toolkit.PathOfTemporary);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string file = Toolkit.NextUUID + ".doc";
            File.Copy(Toolkit.MappingPath(string.Format("{0}/{1}", Toolkit.PathOfReport, Toolkit.TemplateOfStatArticleDetail)), string.Format("{0}/{1}", path, file));

            app = new Word.Application();
            doc = app.Documents.Open(string.Format("{0}/{1}", path, file));

            Word.Bookmark bm = doc.Bookmarks["Time"];
            bm.Range.Text = string.Format("{0:yyyy年MM月dd日}", DateTime.Now);

            bm = doc.Bookmarks["Person"];
            bm.Range.Text = Toolkit.CurrentUserName;

            bm = doc.Bookmarks["During"];
            bm.Range.Text = string.Format("{0:yyyy年MM月dd日}-{1:yyyy年MM月dd日}", st, ed);

            Word.Row row;
            Word.Cell cell;
            Word.Table tbl = doc.Tables[1];

            int iRow = 0;
            foreach (Article t in p)
            {
                iRow++;
                row = tbl.Rows.Add();

                cell = row.Cells[1];
                cell.Range.Text = Convert.ToString(iRow);

                cell = row.Cells[2];
                cell.Range.Text = t.Belong;

                cell = row.Cells[3];
                cell.Range.Text = t.Creator.Name;

                cell = row.Cells[4];
                cell.Range.Text = t.Title;

                cell = row.Cells[5];
                cell.Range.Text = string.Format("{0:yyyy年MM月dd日 HH:mm}", t.Published);
            }

            doc.Save();
            doc.Close(ref ms, ref ms, ref ms);

            doc = null;

            Response.Redirect(string.Format("~/Temps/{0}", file));
        }
        catch (Exception ee)
        {
            MessageBox.Message = ee.StackTrace;
        }
        finally
        {
            if (app != null)
            {
                app.Quit(ref ms, ref ms, ref ms);
                app = null;
            }
        }
    }
    protected void Export2_Click(object sender, EventArgs e)
    {
        DateTime st = DateTime.Parse(string.Format("{0}年{1}月{2}日", Year1.SelectedValue, Month1.SelectedValue, Day1.SelectedValue));
        DateTime ed = DateTime.Parse(string.Format("{0}年{1}月{2}日", Year2.SelectedValue, Month2.SelectedValue, Day2.SelectedValue));

        Word.Application app = null;
        Word.Document doc = null;

        object ms = Type.Missing;

        CmsDataContext db = new CmsDataContext();
        var q = from aA in db.Article
                where aA.Published.CompareTo(st) >= 0 && aA.Published.CompareTo(ed) <= 0
                select aA;

        string district;
        string depart;

        try
        {
            string path = Toolkit.MappingPath(Toolkit.PathOfTemporary);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string file = Toolkit.NextUUID + ".doc";
            File.Copy(Toolkit.MappingPath(string.Format("{0}/{1}", Toolkit.PathOfReport, Toolkit.TemplateOfStatArticleAll)), string.Format("{0}/{1}", path, file));

            app = new Word.Application();
            doc = app.Documents.Open(string.Format("{0}/{1}", path, file));

            Word.Bookmark bm = doc.Bookmarks["Time"];
            bm.Range.Text = string.Format("{0:yyyy年MM月dd日}", DateTime.Now);

            bm = doc.Bookmarks["Person"];
            bm.Range.Text = Toolkit.CurrentUserName;

            bm = doc.Bookmarks["During"];
            bm.Range.Text = string.Format("{0:yyyy年MM月dd日}-{1:yyyy年MM月dd日}", st, ed);

            Word.Row row;
            Word.Cell cell;
            Word.Table tbl = doc.Tables[1];

            int iRow = 0;
            
            #region 在树控件中查询所有单位的名称
            foreach (TreeNode n1 in Departments.Nodes)
            {
                if (!n1.Checked)
                {
                    continue;
                }

                district = n1.Value;

                #region 单位汇总
                iRow++;
                row = tbl.Rows.Add();

                cell = row.Cells[1];
                cell.Range.Text = Convert.ToString(iRow);

                cell = row.Cells[2];
                cell.Range.Text = district;

                cell = row.Cells[3];
                cell.Range.Text = "";

                cell = row.Cells[4];
                cell.Range.Text = Convert.ToString(q.Where(aA => aA.District == district).Count());
                #endregion

                foreach (TreeNode n2 in n1.ChildNodes)
                {
                    if (!n2.Checked)
                    {
                        continue;
                    }

                    depart = n2.Value.Substring(2);

                    #region 分单位汇总
                    iRow++;
                    row = tbl.Rows.Add();

                    cell = row.Cells[1];
                    cell.Range.Text = Convert.ToString(iRow);

                    cell = row.Cells[2];
                    cell.Range.Text = "";

                    cell = row.Cells[3];
                    cell.Range.Text = depart;

                    cell = row.Cells[4];
                    cell.Range.Text = Convert.ToString(q.Where(aA => aA.District == district && aA.Belong == depart).Count());
                    #endregion
                }
            }
            #endregion

            
            doc.Save();
            doc.Close(ref ms, ref ms, ref ms);

            doc = null;

            Response.Redirect(string.Format("~/Temps/{0}", file));
        }
        catch (Exception ee)
        {
            MessageBox.Message = ee.StackTrace;
        }
        finally
        {
            if (app != null)
            {
                app.Quit(ref ms, ref ms, ref ms);
                app = null;
            }
        }
    }
}